/* note.cpp
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Function definitions for reading and writing the noteline.
*/

#include "note.h"

#include <fstream>
#include <cstdlib>

using std::ifstream;
using std::ofstream;
using std::ios;
using std::endl;
using std::getline;
using std::getenv;



// Read the most recent note.
string note_read()
{
	string path = getenv("HOME");
	path += "/.noteline";
	
	ifstream in(path.c_str());
	in.seekg(-1, std::ios::end);
	
	for(size_t pos = in.tellg(); pos > 0; --pos)
	{
		in.unget();
		if(!in || in.peek() == '\n')
			break;
	}
	// Skip past the newline.
	in.get();
	string text;
	getline(in, text);
	
	return text;
}



// Write a new note. If the text begins with a space, it will
// be appended to the most recent note instead of replacing it.
// If the text begins with "REM", it will be added to .reminders.
void note_write(string text)
{
	if(text.empty())
		return;
	
	string path = getenv("HOME");
	
	if(text[0] == ' ')
		text = note_read() + text;
	
	if(text.length() >= 3 && text.substr(0, 3) == "REM")
	{
		// If the text is going to the reminders file, make sure it ends in '%'.
		if(*(text.end() - 1) != '%')
			text += '%';
		path += "/.reminders";
	}
	else
	{
		path += "/.noteline";
		if(text.length() > 170)
		{
			// Make sure the text will fit on the screen. Scroll left if it will not.
			text.erase(text.begin(), text.begin() + text.length() - 170);
		}
	}
	
	ofstream out(path.c_str(), ios::out | ios::app | ios::ate);
	out << text << endl;
}



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */
